package com.example.demo.util;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
public class ResourceUtils {

    public static String upload(MultipartFile file) throws QiniuException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "A5IkKjSH4NKH-L4VjAbvoSLOEKvdIcgyA3A-19n_";
        String secretKey = "hdNtvbguDpajtf0XYh_bubmQf6KwuXDs1q1-c3vV";
        String bucket = "class10";

        String key = file.getOriginalFilename();
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return "http://r9huo9oyy.hn-bkt.clouddn.com/"+defaultPutRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            log.error(r.bodyString());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

